"""
"""

__author__ = "Chad J. Schroeder"
__copyright__ = "Copyright (C) 2005 Chad J. Schroeder"

__revision__ = "$Id$"
__version__ = "0.2"

import os               # Miscellaneous OS interfaces.
import sys              # System-specific parameters and functions.
import time

# Default daemon parameters.
# File mode creation mask of the daemon.
UMASK = 0

# Default working directory for the daemon.
WORKDIR = "/"

# Default maximum for the number of available file descriptors.
MAXFD = 1024

# The standard I/O file descriptors are redirected to /dev/null by default.
if (hasattr(os, "devnull")):
   REDIRECT_TO = os.devnull
else:
   REDIRECT_TO = "/dev/null"
   
def createDaemon():
   """Detach a process from the controlling terminal and run it in the
   background as a daemon.
   """

   try:
      pid = os.fork()
   except OSError, e:
      raise Exception, "%s [%d]" % (e.strerror, e.errno)

   if (pid == 0):	# The first child.
      os.setsid()

      
      try:
         pid = os.fork()	# Fork a second child.
      except OSError, e:
         raise Exception, "%s [%d]" % (e.strerror, e.errno)
      
      if (pid == 0):	# The second child.
         os.chdir(WORKDIR)
         os.umask(UMASK)
      else:
         os._exit(0)	# Exit parent (the first child) of the second child.
   else:
      os._exit(0)	# Exit parent of the first child.
      
   import resource		# Resource usage information.
   maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
   if (maxfd == resource.RLIM_INFINITY):
      maxfd = MAXFD
      
   # Iterate through and close all file descriptors.
   for fd in range(0, maxfd):
      try:
         os.close(fd)
      except OSError:	# ERROR, fd wasn't open to begin with (ignored)
         pass

   os.open(REDIRECT_TO, os.O_RDWR)	# standard input (0)

   os.dup2(0, 1)			# standard output (1)
   os.dup2(0, 2)			# standard error (2)

   return(0)

import os,tempfile,shutil,commands
import pickle
import sys
import time
from crvclient import CRVClientTools

if __name__ == "__main__":

   #retCode = createDaemon()
   retCode=0
    
   procParams = """
   return code = %s
   process ID = %s
   parent process ID = %s
   process group ID = %s
   session ID = %s
   user ID = %s
   effective user ID = %s
   real group ID = %s
   effective group ID = %s
   """ % (retCode, os.getpid(), os.getppid(), os.getpgrp(), os.getsid(0),
          os.getuid(), os.geteuid(), os.getgid(), os.getegid())
   
   open("createDaemon.log", "w").write(procParams + "\n")
   
   inf=open(sys.argv[1],"r")
   clientconf=pickle.load(inf)
   inf.close()
   
   tool=CRVClientTools(clientconf)
   
   #Definition: Active Role = Role that has ProfileProvided=True
   
   #set last run to a very long time ago.
   lastruntime=0
   
   oufname="/var/log/crvclient.puppet.log"
   
   #put the files in place
   # now we have crvclient/certname.crt, certname.prk, certname.puk, pass.txt
   
   roleliststr=tool.doSecureStatusCurlUntilDone("getVMListOfRoles?vmid=%s"%(clientconf.vmid))
   rolelist=roleliststr.split(",")

   while True:
      tool.doSecureStatusCurlUntilDone("setVMLastActiveTime?vmid=%s"%(clientconf.vmid));
      #check all roles to see if they need to be applied
      for irole in rolelist:
         try:
            roleid=int(irole);
         except:
            continue;

         applyType = tool.doSecureStatusCurlUntilDone("getRoleAttr?roleid=%s&name=%s"%(roleid, "doApply"));
         
         if applyType == "setup":
            catalog=tool.doSecureStatusCurlUntilDone("getRoleAttr?roleid=%s&name=%s"%(roleid,"puppetcatalog"));
            tool.doSecureStatusCurlUntilDone("setRoleAttr?roleid=%s&name=%s&value=%s"%(roleid,"doApply","none"));
            (error, warn)=tool.applyPuppetCatalog(catalog,oufname);
            if not error:
               tool.doSecureStatusCurlUntilDone("sendMessageToController?message=%s&messageAbout=%s"%("roleIsUp", roleid));
            else:
               tool.doSecureStatusCurlUntilDone("sendMessageToController?message=%s&messageAbout=%s"%("roleApplyError", roleid));
            tool.doSecureStatusCurlUntilDone("setVMLastActiveTime?vmid=%s"%(clientconf.vmid));
         elif applyType == "update":
            clusterStatus = tool.doSecureStatusCurlUntilDone("getClusterStatus?roleid=%s"%(roleid));
            if clusterStatus == "updating": #make sure cluster is in update stage
               #set update flag False so it doesn't update again (unless something later sets flag back to True)
               tool.doSecureStatusCurlUntilDone("setRoleAttr?roleid=%s&name=%s&value=%s"%(roleid,"updateFlag","False"));
               catalog=tool.doSecureStatusCurlUntilDone("getRoleAttr?roleid=%s&name=%s"%(roleid,"puppetcatalog"));
               tool.doSecureStatusCurlUntilDone("setRoleAttr?roleid=%s&name=%s&value=%s"%(roleid,"doApply","none"));
               (error, warn)=tool.applyPuppetCatalog(catalog,oufname);
               if not error:
                  tool.doSecureStatusCurlUntilDone("sendMessageToController?message=%s&messageAbout=%s"%("roleIsUp", roleid));
               else:
                  tool.doSecureStatusCurlUntilDone("sendMessageToController?message=%s&messageAbout=%s"%("roleApplyError", roleid));
               tool.doSecureStatusCurlUntilDone("setVMLastActiveTime?vmid=%s"%(clientconf.vmid));
         elif applyType == "stop":
            catalog=tool.doSecureStatusCurlUntilDone("getRoleAttr?roleid=%s&name=%s"%(roleid,"puppetcatalog"));
            tool.doSecureStatusCurlUntilDone("setRoleAttr?roleid=%s&name=%s&value=%s"%(roleid,"doApply","none"));
            (error, warn)=tool.applyPuppetCatalog(catalog,oufname);
            if not error:
               tool.doSecureStatusCurlUntilDone("sendMessageToController?message=%s&messageAbout=%s"%("roleStopped", roleid));
            else:
               tool.doSecureStatusCurlUntilDone("sendMessageToController?message=%s&messageAbout=%s"%("roleStopError", roleid));
            tool.doSecureStatusCurlUntilDone("setVMLastActiveTime?vmid=%s"%(clientconf.vmid));

   
      time.sleep(10);
